package com.yy.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yy.mapper.UserMapper;
import com.yy.pojo.param.UserLoginParam;
import com.yy.pojo.param.UserRegisterParam;
import com.yy.pojo.po.UserPO;
import com.yy.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import utils.AesUtil;
import utils.JWTUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Author: lyy
 * Date: 2021/12/13 11:45
 */
@Service
public class UserService {

	@Autowired
	private UserMapper userMapper;

	@Transactional(rollbackFor = Exception.class)
	public void register(UserRegisterParam param){
		param.setAccount(AesUtil.encrypt(param.getAccount()));
		UserPO userPO = new UserPO();
		BeanUtils.copyProperties(param, userPO);
		userPO.setCreateTime(LocalDateTime.now());
		insert(userPO);
	}

	public String login(UserLoginParam param){
		param.setAccount(AesUtil.encrypt(param.getAccount()));
		UserPO userPO = new UserPO();
		BeanUtils.copyProperties(param, userPO);
		UserPO user = select(userPO);
		Assert.notNull(user, "用户名或密码不正确");
		String token = JWTUtils.createToken(user.getId());
		return token;
	}

	public List<UserVO> selectUserList(){
		List<UserPO> userPOList = userMapper.selectList(null);
		List<UserVO> userVoList = userPOList.stream().map(u->{
			UserVO userVO = new UserVO();
			BeanUtils.copyProperties(u, userVO);
			return userVO;
		}).collect(Collectors.toList());
		return userVoList;
	}

	@Transactional(rollbackFor = Exception.class)
	public Integer insert(UserPO userPO){
		userMapper.insert(userPO);
		return userPO.getId();
	}

	public UserPO select(UserPO userPO){
		return userMapper.selectOne(Wrappers.lambdaQuery(UserPO.class)
				.eq(UserPO::getAccount, userPO.getAccount())
				.eq(UserPO::getPassword, userPO.getPassword()));
	}

}
